<template>
  <div>
    <h3 style="text-align:center">{{ title }}</h3>

    <el-tabs type="border-card" v-model="taskSelectedTab">
      <el-tab-pane label="表单信息" name="form-first">
        <component id="printForm" :formReadOnly="formReadOnly" v-if="formCustom === 'N'"
                   :class="formReadOnly?'readonly':''" ref="form" :businessId="businessId" :is="form"></component>

        <PreviewForm id="printForm" v-if="formCustom !== 'N'" :readonly="true" ref="form"/>
      </el-tab-pane>
      <el-tab-pane label="流程图" name="form-two">
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>流程图</span>
            <img :src="imgUrl" width="100%" style="margin:0 auto"/>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <el-card style="margin-top:10px; padding-bottom:66px" v-if="!instanceId || taskId">
      <el-form size="small" :model="auditForm" ref="auditForm" label-width="120px">
        <el-col :span="16">
          <el-form-item v-if="!instanceId" label="流程标题" prop="title">
            <el-input
              placeholder="请输入流程标题"
              v-model="title">
            </el-input>
          </el-form-item>
          <el-form-item v-if="taskId" label="审批信息" prop="message">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              v-model="auditForm.message">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="任意跳转" prop="nodeCode">
            <el-select v-model="auditForm.nodeCode" placeholder="请选择跳转节点">
              <el-option
                v-for="dict in anyNodes"
                :key="dict.nodeCode"
                :label="dict.nodeName"
                :value="dict.nodeCode"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item>
            <el-checkbox v-model="isCC">是否抄送</el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item v-if="isCC" :rules="[
              {required: true, message: '用户不能为空', trigger: 'blur'}
            ]" prop="userIds" label="抄送给">
            <user-select :value="auditForm.userIds" @getValue='(value) => {auditForm.userIds=value}'>></user-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-card>

    <div class="flowFooter">
      <el-button type="success" @click="handleBtn('PASS')" plain>提交</el-button>
      <el-button type="primary" @click="handleBtn('1')" plain>转办</el-button>
      <el-button type="primary" @click="handleBtn('3')" plain>委派</el-button>
      <el-button type="warning" @click="handleBtn('stop')" plain>暂存</el-button>
      <el-button type="danger" @click="handleBtn('TERMINATION')" plain>终止</el-button>
      <el-button type="info" @click="handleBtn('REJECT')" plain>退回</el-button>
    </div>

    <!-- 权限标识：选择用户 -->
    <el-dialog :title="`${dialogTitle}用户选择`" v-if="userVisible" :visible.sync="userVisible" width="80%" append-to-body>
      <selectUser :postParams="postParams" :type="dialogTitle" :selectUser.sync="assigneePermission"
                  :userVisible.sync="userVisible" @handleUserSelect="handleUserSelect"></selectUser>
    </el-dialog>

  </div>
</template>

<script>
import SelectUser from '@/components/SelectUser'
import UserSelect from '@/components/UserSelect'
import PreviewForm from '@/views/flow/form/GenerateFlowForm'
import UserSelectDialog from '@/components/UserSelect/UserSelectDialog'
import {flowImage} from "@/api/flow/definition";
import {anyNodeList, approve, termination, interactiveType, hisTaskList} from "@/api/flow/execute";

export default {
  components: {
    SelectUser,
    UserSelect,
    UserSelectDialog,
    PreviewForm
  },
  watch: {
    isAssign(val) {
      if (!val) {
        this.assignee = null
      }
    }
  },
  data() {
    return {
      form: null,
      formCustom: '',
      formPath: '',
      taskSelectedTab: 'form-first',
      historicTaskList: [],
      definitionId: '',
      title: '',
      businessId: '',
      instanceId: '',
      formReadOnly: false,
      procDefKey: '',
      taskId: '',
      taskFormData: {},
      taskDefKey: '',
      status: '',

      buttons: [],
      isCC: false,
      isAssign: false,
      printObj: {
        id: 'printForm',
        popTitle: '',
        extraCss: '',
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>'
      },
      anyNodes: [],
      auditForm: {
        message: '',
        type: '',
        status: '',
        userIds: null,
        assignee: null
      },
      imgUrl: '',
      dialogTitle: "",
      postParams: {},
      userVisible: false,
      assigneePermission: null
    }
  },
  created() {
    this.init()
    this.getFlowImage(this.instanceId)
    if (this.formCustom === 'N') { // 读取外置表单
      if (this.formPath === '/404') {
        this.form = null
        this.$message.info('没有关联流程表单!')
      } else {
        //todo 跳转页面
      }
    } else { // 读取动态表单
      this.$nextTick(() => {
        if (this.formPath === '/404') {
          this.$refs.form.createForm('')
        } else {
          this.$refs.form.createForm(this.definitionId, this.businessId)
        }
      })

    }

    anyNodeList(this.instanceId).then(response => {
      if (response.data) {
        this.anyNodes = response.data;
      }
    });

    // 读取历史任务列表
    if (this.businessId) {
      hisTaskList(this.businessId).then(({data}) => {
        console.log(data)
        this.historicTaskList = data
      })
    }
  },
  methods: {
    init() {
      this.taskId = this.$route.query.taskId
      this.title = this.$route.query.title
      this.businessId = this.$route.query.businessId
      this.instanceId = this.$route.query.instanceId
      this.taskSelectedTab = 'form-first'
      this.definitionId = this.$route.query.definitionId
      this.formCustom = this.$route.query.formCustom
      this.formPath = this.$route.query.formPath

      this.procDefKey = this.$route.query.procDefKey
      this.taskDefKey = this.$route.query.taskDefKey
      this.status = this.$route.query.status
      this.printObj.popTitle = this.title
      this.formReadOnly = this.$route.query.formReadOnly !== undefined && this.$route.query.formReadOnly !== 'false' && this.$route.query.formReadOnly !== false
      this.isCC = false
      this.isAssign = false
      this.auditForm.assignee = null
      this.auditForm.userIds = null
      this.auditForm.message = ''
    },
    getFlowImage(instanceId) {
      flowImage(instanceId).then(response => {
        this.imgUrl = "data:image/gif;base64," + response.data;
      });
    },
    // 终止
    stop() {
      this.$confirm(`确定终止流程吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      })
    },
    handleBtn(skipType) {
      if (skipType == 'PASS' || skipType == 'REJECT') {
        approve({
          taskId: this.taskId,
          skipType: skipType,
          message: this.message,
          nodeCode: this.nodeCode,
          flowStatus: this.flowStatus
        }).then(response => {
          this.$modal.msgSuccess("审批成功");
          this.$tab.closePage();
        });
      } else if (skipType == 'TERMINATION') {
        termination({code: this.code, instanceId: this.instanceId, businessId: this.businessId}).then(response => {
          this.$modal.msgSuccess("终止成功");
          this.$tab.closePage();
        });
      } else if (skipType == '1' || skipType == '3') {
        this.assigneePermission = null;
        this.dialogTitle = skipType == '1' ? '转办' : '委派';
        // api.getTaskById(this.taskId).then(res => {
        //   this.form.assigneePermission = res.data.assigneePermission ? res.data.assigneePermission.split(",") : [];
        // });
        this.userVisible = true;
        this.postParams = {
          url: "interactiveTypeSysUser",
          taskId: this.taskId,
          operatorType: skipType
        };
      }
    },
    // 获取选中用户数据
    handleUserSelect(checkedItemList) {
      this.assigneePermission = checkedItemList.map(e => {
        return e.userId;
      });
      let assigneePermission = JSON.parse(JSON.stringify(this.assigneePermission));
      let operatorTypeObj = {
        "转办": "2",
        "委派": "3",
      };
      interactiveType(this.taskId, Array.isArray(assigneePermission) ? assigneePermission.join(',') : assigneePermission,  operatorTypeObj[this.dialogTitle])
        .then(() => {
          this.$modal.msgSuccess(`${this.dialogTitle}成功`);
          this.$tab.closePage();
        });
    }
  }
}
</script>
<style lang="scss" scoped>
.flowFooter {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 66px;
  z-index: 999;
  background: #fff;
  -webkit-box-shadow: 0 -3px 5px 0 rgba(0, 0, 0, .12);
  box-shadow: 0 -3px 5px 0 rgba(0, 0, 0, .12);
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;

  display: flex;
  -webkit-transition: inline-block 0.3s, left 0.3s, width 0.3s, margin-left 0.3s, font-size 0.3s;
  transition: inline-block 0.3s, left 0.3s, width 0.3s, margin-left 0.3s, font-size 0.3s;
}
</style>
